package br.com.fitness.infrastructure;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.fitness.core.AbstractEntity;

public abstract class AbstractRepositoryImpl<T extends AbstractEntity, E extends Serializable>
		extends HibernateDaoSupport implements AbstractRepository<T, E> {
	protected Class<T> entityClass;
	
	public AbstractRepositoryImpl(Class<T> ec) {
		this.entityClass = ec;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public T findById(E id) {
		return getHibernateTemplate().get(entityClass, id);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public List<T> list() {
		return getSession().createCriteria(entityClass).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void persist(T entity) {
		getHibernateTemplate().save(entity);

	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void update(T entity) {
		getHibernateTemplate().merge(entity);

	}

}
